package com.xuzz.study.io.nio;

import com.xuzz.study.io.netty.rpc.provicer.Server;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioServer {
    public static void main(String[] args) throws Exception {
        //创建SeverSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //Selector里面有很多SelectorKey,SelectorKey有关联对应的Channel,以及该channel关心的事件
        Selector selector = Selector.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(6666);
        serverSocketChannel.socket().bind(inetSocketAddress);
        serverSocketChannel.configureBlocking(false);

        //把服务端channel，注册到selector中，并且关系accept事件
        //也就是，有客户端channel连接，那么selector的selectedKeys集合中就有SelectorKey。
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while(true){
            //等待1秒钟，没有连接就不阻塞，去干其他的
            if(0==selector.select(1000))
            {
                System.out.println("服务器等待了1秒,无连接");
                continue;
            }

            //如果不是0，则说明有连接，那就把有事件发生的SelectionKey拿到
            //注意：SelectionKey里面持有对应的服务端channel
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历事件
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while(keyIterator.hasNext())
            {
                SelectionKey selectionKey = keyIterator.next();
                if(selectionKey.isAcceptable())
                {
                    //做连接处理
                    //接到了连接，那么它肯定是个channel，同样的把该channel register into the selector
                    //注意，这个时候的SelectionKey中的Channel，是ServerSocketChannel，因为是ServerSocketChannel接到了客户端连接
                    SocketChannel acceptChannel = serverSocketChannel.accept();
                    acceptChannel.configureBlocking(false);
                    //也可以如下获取客户端channel
//                    SocketChannel socketChannel1 = ((ServerSocketChannel) selectionKey.channel()).accept();
                    System.out.println("收到1个客户端的连接:"+acceptChannel.getRemoteAddress());

                    //同时给这个channel关联1个buffer,关注这个Channel的read事件
                    acceptChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                else if(selectionKey.isReadable())
                {
                    //读
                    //这个时候selectorKey，是客户端channel的
                    //因为客户端channel在连接的时候，已经注册到selector中了，并关注了read事件
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer= (ByteBuffer)selectionKey.attachment();
                    socketChannel.read(buffer);
                    System.out.println("from client:"+new String(buffer.array()));
                }
                else if(selectionKey.isWritable())
                {
                    //写
                }

                //这个事件处理完成了，则要把这个事件删除，防止重复操作
                selectionKeys.remove(selectionKey);
            }
        }
    }
}
